package dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import pojo.Sanpham;
import pojo.Taikhoan;
import util.HibernateUtil;
import util.IVisitor;

public class TaikhoanDAO extends AbstractDAO<Taikhoan, Integer>{


	@Override
	protected Class getPOJOClass() {
		// TODO Auto-generated method stub
		return Taikhoan.class;
	}

	@Override
	protected Query MakeHQL() {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	public Taikhoan AcceptTaiKhoan(String username, String password)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "from Taikhoan tk where tk.tendangnhap=:username and tk.matkhau=:password";
        Query query = session.createQuery(hql);
        query.setString("username", username);
        query.setString("password", password);
        
        Taikhoan taikhoan = (Taikhoan)query.uniqueResult();
        
        session.close();
        
        return taikhoan;
	}
	
	public boolean IsValidUsername(String username)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "from Taikhoan tk where tk.tendangnhap=:username";
        Query query = session.createQuery(hql);
        query.setString("username", username);
        
        Taikhoan taikhoan = (Taikhoan)query.uniqueResult();
        
        session.close();
		
        if(taikhoan != null)
        	return true;
		
		return false;
	}


	public List<Taikhoan> GetTaiKhoanTheoKiTuBatDau(String kiTuBatDau) {
		
		if ("-1" == kiTuBatDau)
			return getList();		
		
		String hql = "select tk from Taikhoan tk " +
				"where lower(tk.tendangnhap) like '" + kiTuBatDau.toLowerCase() + "%'";
		
		System.out.println(hql);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Query selectClause = session.createQuery(hql);

		List<Taikhoan> lstTaiKhoan = selectClause.list();

		System.out.println(lstTaiKhoan.size());
		session.close();
		return lstTaiKhoan;
	}

    //---------------QNReck Visitor Template-----------
    public void accept(IVisitor visitor, String searchKey)
    {
    	visitor.accept(this, searchKey);
    }
}
